package com.summer.controller;


import com.auth0.jwt.exceptions.TokenExpiredException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.summer.entity.TbActivityinfo;
import com.summer.entity.TbRole;
import com.summer.entity.TbUserinfo;
import com.summer.mapper.TbAccountBindMapper;
import com.summer.mapper.TbActivityinfoMapper;
import com.summer.mapper.TbUserinfoMapper;
import com.summer.utils.JwtToken;
import com.summer.utils.MyUtil;
import com.summer.utils.ResponseEntity;
import com.summer.vo.Activity;
import com.summer.vo.ActivityVo;
import com.summer.vo.MyActivity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *测试通过20:03
 * @author summer502
 * @since 2021-03-31
 */
@CrossOrigin
@RestController
@RequestMapping("/tb-activityinfo")
@Transactional
@Api(value = "TbActivityinfoController", description = "活动基本信息api")

public class TbActivityinfoController {
    /**
            private Integer activity_id;
            private Integer create_user_id;
            private String create_user_name;
            private String activity_type_name;
            private String activity_name;
            private String activity_description;
            private String activity_start_time;
            private String signup_start_time;
            private String signup_end_time;
            private Integer plan_num;
            private String contactName;
            private String contactNum;
            private String contactEmail;
            private Integer isDelete;
     */

    Boolean flag;
    MyUtil myUtil = new MyUtil();
    @Autowired(required =false)
    TbActivityinfoMapper tbActivityinfoMapper;
    @Autowired(required =false)
    TbUserinfoMapper tbUserinfoMapper;

    /**
     * 超级管理员添加活动
     * @param activity_type_name
     * @param create_user_id
     * @param create_user_name
     * @param activity_name
     * @param activity_description
     * @param plan_num
     * @param contactName
     * @param contactNum
     * @param contactEmail
     * @param activity_start_time
     * @param activity_end_time
     * @param signup_start_time
     * @param signup_end_time
     * @param Authorization
     * @return
     * @throws IOException
     * @throws TokenExpiredException
     */

    @ApiOperation("超级管理员添加活动")
    @PostMapping("/teacher/addActivityinfo")
    @ResponseBody
    public ResponseEntity addActivityinfo(@RequestParam(required = false) String activity_type_name,
                                     @RequestParam(required = false) int create_user_id,
                                     @RequestParam(required = false) String create_user_name,
                                     @RequestParam(required = false) String activity_name,
                                     @RequestParam(required = false) String activity_description,
                                     @RequestParam(required = false) int plan_num,
                                     @RequestParam(required = false) String contactName,
                                     @RequestParam(required = false) String contactNum,
                                     @RequestParam(required = false) String contactEmail,
                                     @RequestParam(required = false) String activity_start_time,
                                     @RequestParam(required = false) String activity_end_time,
                                     @RequestParam(required = false) String signup_start_time,
                                     @RequestParam(required = false) String signup_end_time,
                                     @RequestHeader String Authorization
    ) throws IOException, TokenExpiredException {
        ResponseEntity responseEntity;
        String token = Authorization;
        //parentRoleId
        //判断token是否存在或过期
        if (flag = myUtil.judgeToken(token)){
            responseEntity = ResponseEntity.forbidden();
            responseEntity.putDataValue("msg","token不存在或已过期");
            return responseEntity;
        }
        TbUserinfo tbUserinfo = JwtToken.unsign(token, TbUserinfo.class);
        //用户角色，分微信用户和老师用户，1代表微信用户，2代表老师用户,默认为微信用户
        if (tbUserinfo.getUserId()!=1&&tbUserinfo.getUserId()>0){
            responseEntity = ResponseEntity.unauthorized();
            responseEntity.putDataValue("msg","权限错误");
            responseEntity.putDataValue("timestamp",myUtil.getTime());
            return responseEntity;
        }
        //根据user_jobNumber查询数据库是否有该用户存在，不存在则注册，存在则注册失败
        QueryWrapper<TbActivityinfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("activity_name", activity_name);
        TbActivityinfo tbActivityinfo = tbActivityinfoMapper.selectOne(queryWrapper);
        //User userFromBase = userDao.selectById(user_name);
        if (tbActivityinfo == null){
            responseEntity = ResponseEntity.ok();
            TbActivityinfo tbActivityinfo1 = new TbActivityinfo();
            tbActivityinfo1.setActivityTypeName(activity_type_name);
            tbActivityinfo1.setActivityDescription(activity_description);
            tbActivityinfo1.setActivityStartTime(activity_start_time);
            tbActivityinfo1.setActivityEndTime(activity_end_time);
            tbActivityinfo1.setActivityName(activity_name);
            tbActivityinfo1.setContactEmail(contactEmail);
            tbActivityinfo1.setContactName(contactName);
            tbActivityinfo1.setContactNum(contactNum);
            tbActivityinfo1.setCreateUserId(create_user_id);
            tbActivityinfo1.setCreateUserName(create_user_name);
            tbActivityinfo1.setPlanNum(plan_num);
            tbActivityinfo1.setSignupEndTime(signup_end_time);
            tbActivityinfo1.setSignupStartTime(signup_start_time);
            tbActivityinfoMapper.insert(tbActivityinfo1);
            responseEntity.putDataValue("activity_id",tbActivityinfo1.getActivity_id());
            responseEntity.putDataValue("msg","活动添加成功");
        }else {
            responseEntity = ResponseEntity.badRequest();
            responseEntity.putDataValue("msg","活动名已存在,活动添加失败");
        }
        return responseEntity;
    }

    /**
     * 活动列表
     * @return
     * @throws IOException
     */
    @ApiOperation("活动列表")
    @PostMapping("/web/ActivityInfoList")
    @ResponseBody
    public ResponseEntity ActivityInfoList() throws IOException {
        ResponseEntity responseData;
        QueryWrapper<TbActivityinfo> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete",0);
        List<TbActivityinfo> list = tbActivityinfoMapper.selectList(wrapper);
        responseData = ResponseEntity.ok();
        responseData.putDataValue("list",list);
        responseData.putDataValue("msg","成功");
        return responseData;
    }

    /**
     * 根据id删除活动信息
     * @param activity_id
     * @param Authorization
     * @return
     * @throws IOException
     */
    @ApiOperation("根据id删除活动信息")
    @PutMapping("/web/deleteActivityInfo")
    @ResponseBody
    public ResponseEntity deleteActivityInfo(@RequestParam(required = true) Integer activity_id,@RequestHeader String Authorization)throws IOException{
        ResponseEntity responseEntity;
        String token=Authorization;
        if(flag=myUtil.judgeToken(token)){
            responseEntity=ResponseEntity.forbidden();
            responseEntity.putDataValue("msg","token不存在或已过期");
            return responseEntity;
        }
        TbUserinfo users=JwtToken.unsign(token,TbUserinfo.class);
        if(users==null){
            responseEntity=ResponseEntity.notFound();
            responseEntity.putDataValue("msg","用户不存在");
            return responseEntity;
        }else if(users.getRoleId()==1) {
            TbActivityinfo tbActivityinfo = tbActivityinfoMapper.selectById(activity_id);
            if(tbActivityinfo!=null){
                int is_delete = 1;
                tbActivityinfo.setIsDelete(is_delete);
                tbActivityinfoMapper.updateById(tbActivityinfo);
                responseEntity=ResponseEntity.ok();
                responseEntity.putDataValue("msg","删除成功");
                return responseEntity;
            }
        }
        responseEntity=ResponseEntity.unauthorized();
        responseEntity.putDataValue("msg","没有权限");
        return responseEntity;
    }

    /**
     * 根据activity_id查询活动信息
     * @param activity_id
     * @param Authorization
     * @return
     * @throws IOException
     */
    @ApiOperation("根据activity_id查询活动信息")
    @PutMapping("/web/selectByActivityInfoId")
    @ResponseBody
    public ResponseEntity selectByActivityInfoId(@RequestParam(required = true) Integer activity_id, @RequestHeader String Authorization) throws IOException {
        ResponseEntity responseEntity;
        String token = Authorization;
        if (flag =myUtil.judgeToken(token)) {
            responseEntity = ResponseEntity.forbidden();
            responseEntity.putDataValue("msg", "token不存在或已过期");
            return responseEntity;
        }
        TbUserinfo users = JwtToken.unsign(token, TbUserinfo.class);
        if (users == null) {
            responseEntity = ResponseEntity.notFound();
            responseEntity.putDataValue("msg", "用户不存在");
            return responseEntity;
        } else if (users.getRoleId()==1) {
            responseEntity=ResponseEntity.ok();
            TbActivityinfo tbActivityinfo = tbActivityinfoMapper.selectById(activity_id);
            responseEntity.putDataValue("tbActivityInfo",tbActivityinfo);
            return responseEntity;
        }
        responseEntity=ResponseEntity.unauthorized();
        responseEntity.putDataValue("msg","没有权限");
        return responseEntity;
    }

    /**
     * 超级管理员修改活动信息
     * @param activity_id
     * @param activity_type_name
     * @param create_user_id
     * @param create_user_name
     * @param activity_name
     * @param activity_description
     * @param plan_num
     * @param contactName
     * @param contactNum
     * @param contactEmail
     * @param activity_start_time
     * @param activity_end_time
     * @param signup_start_time
     * @param signup_end_time
     * @param Authorization
     * @return
     * @throws IOException
     */
    @ApiOperation("网页超级管理员修改活动信息")
    @PutMapping("/web/updateActivityInfo")
    @ResponseBody
    public ResponseEntity updateActivityInfo(@RequestParam(required = true) int activity_id,
                                             @RequestParam(required = false) String activity_type_name,
                                             @RequestParam(required = false) int create_user_id,
                                             @RequestParam(required = false) String create_user_name,
                                             @RequestParam(required = false) String activity_name,
                                             @RequestParam(required = false) String activity_description,
                                             @RequestParam(required = false) int plan_num,
                                             @RequestParam(required = false) String contactName,
                                             @RequestParam(required = false) String contactNum,
                                             @RequestParam(required = false) String contactEmail,
                                             @RequestParam(required = false) String activity_start_time,
                                             @RequestParam(required = false) String activity_end_time,
                                             @RequestParam(required = false) String signup_start_time,
                                             @RequestParam(required = false) String signup_end_time,
                                             @RequestHeader String Authorization) throws IOException {
        ResponseEntity responseEntity;
        String token = Authorization;
        if (flag =myUtil.judgeToken(token)) {
            responseEntity = ResponseEntity.forbidden();
            responseEntity.putDataValue("msg", "token不存在或已过期");
            return responseEntity;
        }
        TbUserinfo users = JwtToken.unsign(token, TbUserinfo.class);
        if (users == null) {
            responseEntity = ResponseEntity.notFound();
            responseEntity.putDataValue("msg", "用户不存在");
            return responseEntity;
        } else if (users.getRoleId()!=1) {
            responseEntity = ResponseEntity.unauthorized();
            responseEntity.putDataValue("msg", "没有权限");
            return responseEntity;

        } else {
            responseEntity = ResponseEntity.ok();
            TbActivityinfo tbActivityInfo1 = tbActivityinfoMapper.selectById(activity_id);
            QueryWrapper<TbActivityinfo> wrapper = new QueryWrapper<>();
            wrapper.eq("activity_name",activity_name);
            TbActivityinfo tbActivityinfo= tbActivityinfoMapper.selectOne(wrapper);
            if(tbActivityinfo==null){
                tbActivityInfo1.setActivityTypeName(activity_type_name);
                tbActivityInfo1.setActivityDescription(activity_description);
                tbActivityInfo1.setActivityStartTime(activity_start_time);
                tbActivityInfo1.setActivityEndTime(activity_end_time);
                tbActivityInfo1.setActivityName(activity_name);
                tbActivityInfo1.setContactEmail(contactEmail);
                tbActivityInfo1.setContactName(contactName);
                tbActivityInfo1.setContactNum(contactNum);
                tbActivityInfo1.setCreateUserId(create_user_id);
                tbActivityInfo1.setCreateUserName(create_user_name);
                tbActivityInfo1.setPlanNum(plan_num);
                tbActivityInfo1.setSignupEndTime(signup_end_time);
                tbActivityInfo1.setSignupStartTime(signup_start_time);
                tbActivityinfoMapper.updateById(tbActivityInfo1);
                responseEntity.putDataValue("msg", "活动信息修改成功");
                return responseEntity;
            }
           else
            {
                responseEntity = ResponseEntity.unauthorized();
                responseEntity.putDataValue("msg", "活动名已经存在");
                return responseEntity;
            }
        }
    }

    /**
     * 根据活动分类名查询活动信息
     * @param activity_type_name
     * @param Authorization
     * @return
     * @throws IOException
     */

    @ApiOperation("根据活动分类名查询活动信息")
    @PutMapping("/web/selectByActivityInfoType_name")
    @ResponseBody
    public ResponseEntity selectByActivityInfoType_name(@RequestParam(required = true) String activity_type_name, @RequestHeader String Authorization) throws IOException {
        ResponseEntity responseEntity;
            responseEntity=ResponseEntity.ok();
            QueryWrapper<TbActivityinfo> queryWrapper =new QueryWrapper<>();
            queryWrapper.eq("activity_type_name",activity_type_name);
            TbActivityinfo tbActivityinfo = tbActivityinfoMapper.selectOne(queryWrapper);
            responseEntity.putDataValue("tbActivityInfo",tbActivityinfo);
            return responseEntity;
    }

    /**
     *
     * @param openid
     * @return
     * @throws IOException
     */
    @ApiOperation("查询自己参加的活动列表")
    @PutMapping("/web/selectByActivityInfoUser")
    @ResponseBody//@RequestHeader String Authorization
    public ResponseEntity selectByActivityInfoUser(@RequestParam(required = true)String openid) throws IOException {
        ResponseEntity responseEntity;
        QueryWrapper<TbUserinfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("openid",openid);
        TbUserinfo tbUserinfo = tbUserinfoMapper.selectOne(queryWrapper);
        if(tbUserinfo==null){
            responseEntity= ResponseEntity.forbidden();
            responseEntity.putDataValue("msg","还没登录");
            return  responseEntity;
        }
        responseEntity=ResponseEntity.ok();
        List<MyActivity> tbActivityinfo = tbActivityinfoMapper.selectListMyactivity(tbUserinfo.getOpenid());
        responseEntity.putDataValue("tbActivityInfo",tbActivityinfo);
        return responseEntity;
    }

    /**
     * 时间戳的活动列表
     * @return
     * @throws IOException
     */
    @ApiOperation("时间戳的活动列表")
    @PutMapping("/web/selectByActivityListBytTime")
    @ResponseBody
    public ResponseEntity selectByActivityListBytTime() throws IOException {
        ResponseEntity responseEntity;
        responseEntity=ResponseEntity.ok();
//        QueryWrapper<MyActivity> queryWrapper =new QueryWrapper<>();
//        queryWrapper.eq("user_id",tbUserinfo.getUserId());
//        queryWrapper.eq("name",tbUserinfo.getNickname());

        List<Activity> tbActivityinfo = tbActivityinfoMapper.list();
//        Map<String, List<Activity>> collect = tbActivityinfo.stream().collect(Collectors.groupingBy(Activity::getTimes));
        LinkedHashMap<String, List<Activity>> collect = tbActivityinfo.stream().
                sorted(Comparator.comparing(Activity::getTimes,Comparator.reverseOrder())).
                collect(Collectors.groupingBy(Activity::getTimes,LinkedHashMap::new, Collectors.toList()));
        List<ActivityVo> voList = new ArrayList<>();
        ActivityVo vo;
        for(String key:collect.keySet()) {
            vo = new ActivityVo();
            vo.setTimes(key);
            vo.setList(collect.get(key));
            voList.add(vo);
        }

        responseEntity.putDataValue("list",voList);
        return responseEntity;
    }




}
